﻿using Ec.NETCoreFramework.Common.Core.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Ec.NETCoreFramework.Common.Core.Serializer
{
    /// <summary>
    /// 字节序列化
    /// 2017-05-08 by shaipe
    /// </summary>
    public static class ProtoBufSerializer
    {
		// 序列化,.反序列化
		public static byte[] Serializeby(object obj)
		{
			using (var stream = new MemoryStream())
			{
				ProtoBuf.Serializer.Serialize(stream, obj);
				return stream.ToArray();
			}
		}
		/// <summary>
		/// 序列化
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="t"></param>
		/// <returns></returns>
		public static string Serialize<T>(T t)
		{
			using (MemoryStream ms = new MemoryStream())
			{
				ProtoBuf.Serializer.Serialize<T>(ms, t);
				return Encoding.UTF8.GetString(ms.ToArray());
			}
		}
		/// <summary>
		/// 反序列化
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="content"></param>
		/// <returns></returns>
		public static T DeSerialize<T>(byte[] content)
		{
			using (MemoryStream ms = new MemoryStream(content))
			{
				T t = ProtoBuf.Serializer.Deserialize<T>(ms);
				return t;
			}
		}
	}
}
